package com.moana.buyTicket.util;

import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.google.gson.Gson;
import com.moana.buyTicket.util.email.EmailSender;
import com.moana.buyTicket.util.BaseResult;

/**
 * 平台对外消息中心（邮件）
 * @author dzp
 *
 */
public class MessageCenter {
	
	
	/**
	 * 发送消息
	 * @param bean
	 * @return 按位与 1表示发送短信成功 2表示发送微信成功 4表示发送邮件成功
	 */
	public static int sendMsg(MessageBean bean) {
		int result=0;
		if(bean.getMsgType()<=0){
			return result;
		}
		String content=format(bean.getModelBean(),bean.getModel());
		if((bean.getMsgType()&MessageBean.MSG_SMS)>0){
			if(sendSMS(bean.getMobile(), content)){
				result+=MessageBean.MSG_SMS;
			}
		}
		if((bean.getMsgType()&MessageBean.MSG_EMAIL)>0){
			if(sendEmail(bean.getEmail(),bean.getSubject(), content)){
				result+=MessageBean.MSG_EMAIL;
			}
		}
		return result;
	}
	


	/**
	 * 发送短信（未开发）
	 * @param mobile
	 * @param content
	 */
	public static boolean sendSMS(String mobile, String content) {
		try {
			//发送短信（未开发）
			return true;
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
		return false;
	}
	/**
	 * 发送邮件
	 * @param email
	 * @param subject
	 * @param content
	 */
	public static boolean sendEmail(String email,String subject, String content) {
		try {
			return new EmailSender().send(email, subject, content);
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
		return false;
	}

	/**
	 * 根据值替换模板(${parameter})
	 * @param value
	 * @param model
	 * @return
	 */
	@SuppressWarnings("unchecked")
	private static String format(Object value, String model) {
		if(value==null||model==null){
			return model;
		}
		StringBuilder sb = new StringBuilder(model);
		Pattern p = Pattern.compile("$\\{(.*?)\\}");
		Matcher m = p.matcher(model);
		Gson json =new Gson();
		HashMap<String, Object> map = json.fromJson(json.toJson(value),HashMap.class);
		int offset = 0;
		while (m.find()) {
			Object item =  map.get(m.group(1));
			String tmp =item==null?"":item.toString();
			if (tmp == null)
				tmp = "";
			sb.replace(m.start() + offset, m.end() + offset, tmp);
			offset += tmp.length() - (m.end() - m.start());
		}
		return sb.toString();
	}
}
